<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');


class Login extends CI_Controller {
    public function __construct(){
        parent::__construct();
        $this->load->helper('url');

    }
    private $_errors = array();
    /**
     * 用户登录模块
     * 判断是否已经登录，已经登录者转入后台首页
     */
    public function index(){
        if(!empty($_POST)){
            $username = $this->input->post('username');
            if(empty($username)){
                $this->_errors['empty_username'] = '请填写用户名！';
            }
            $password = $this->input->post('password');
            if(empty($password)){
                $this->_errors['empty_password'] = '请填写密码！';
            }
            $verify = $this->input->post('verify');
            if(empty($verify )){
                $this->_errors['empty_verify'] = '请填写验证码！';
            }
            $cookie_v = $this->input->cookie('verify');

            $this->load->library('Auth');
            if(!empty($verify) and Auth::decode_pwd(strtolower($verify)) != $cookie_v){
                $this->_errors['error_verify'] = '验证码错误！';
                if(IS_AJAX) show_error(implode('<br/>',$this->_errors),300,'验证码错误！');
            }
            if(!empty($username) and !empty($password) and empty($this->_errors)){
                $this->load->model('admin/admin_user_model');
                $user_arr= $this->admin_user_model->get_admin_user_by_name($username);

                $password = Auth::decode_pwd($password);            
                if(empty($user_arr) or $password != $user_arr['password'])
                {     
                	$this->_errors['error_password'] = '用户名或密码错误！';
	            	if(IS_AJAX) show_error(implode('<br/>',$this->_errors),300,'用户名或密码错误！'); 
	            	
                }else{
                    $token = Auth::get_token_admin_by_user($user_arr);
                    $this->input->set_cookie('token',$token,0);
                    $this->input->set_cookie('account',$user_arr['account'],0);
                    //$this->input->set_cookie('soft_id',$soft_id,0);
                    $this->admin_user_model->db->where('id', $user_arr['id']);
                    $this->admin_user_model->db->update('admin_user', array('last_login_time'=>date('YmdHis'),'last_login_ip'=>$_SERVER ['REMOTE_ADDR'],'login_count'=>intval($user_arr['login_count'])+1));
                    $this->admin_user_model->get_admin_user_auth($user_arr['id'],1,false);//登录后重新生成用户权限缓存。
                    if(IS_AJAX){
                        $str = '<script>location.reload();</script>';
                        status(200, '操作成功'.$str,'','','closeCurrent','reload');
                    }
                    $this->load->helper('url');
                    redirect('/admin/main/index', 'refresh');
                    return true;
                }
            }
        }
        if(IS_AJAX){
            $this->load->view('admin/login/ajax',$data=array('verify'=>$this->captcha()));
        }else{
            $this->load->view('admin/login/index',$data=array('verify'=>$this->captcha(),'errors'=>$this->_errors));
        }
    }

    /**
     * 验证码html获取
     * captcha
     */
    private function captcha(){
        $this->load->helper('captcha');
        $vals = array(
            'img_path' => 'Public/images/captcha/',
            'img_url' => '/Public/images/captcha/',
            'img_width' => '75',
            'img_height' => 24,
            'expiration' => 7200
        );
        $cap = create_captcha($vals);
        //$this->input->cookie('verify',$cap['word']);
        /*$cookie = array(
            'name'   => 'verify',
            'value'  => $cap['word'],
            //'expire' => '0',
            //'domain' => '.sdf.pw',
            //'path'   => '/',
            //'prefix' => 'SDF_',
            //'secure' => TRUE
        );
        $this->input->set_cookie($cookie);echo 'a';*/
        $this->load->library('Auth');
        $this->input->set_cookie('verify',Auth::decode_pwd(strtolower($cap['word'])),0);
        return $cap['image'];
    }

    /**
     * 验证登录是否成功
     * 如果是ajax，返回登录状态嘛
     * 非ajax时，如果成功，跳转到后台首页，失败，返回登录页面。
     */
    public function verify(){
        echo $this->captcha();
    }

    
    /**
     * 修改密码页面
     */
    /*public function change_pwd(){
    	$this->load->helper('url');
    	$this->load->model('admin_user_model');
    	$this->load->helper('cookie');
		$data['account'] = get_cookie('account');
    	$this->load->view('login/change_pwd',$data);
    }*/
    
    /**
     * 提交修改密码
     */
    /*public function post_change_pwd(){
    	$this->load->helper('url');
    	$this->load->library('Auth');
    	$this->load->model('admin_user_model');
    	$account = $this->input->get_post('account');
    	$pwd = $this->input->get_post('pwd');
    	$pwd1 = $this->input->get_post('pwd1');
    	$pwd2 = $this->input->get_post('pwd2');	
    	if(!$pwd1) status(300, '新密码不能为空!');
		if($pwd1 != $pwd2) status(300, '两次输入的密码不一致!');
		
		$user_arr= $this->admin_user_model->get_admin_user_by_name($account);    	
	    $password = Auth::decode_pwd($pwd);            
	    if(empty($user_arr) or $password != $user_arr['password']){     
			status(300, '用户名或密码错误!');
		}else{
			$this->load->database();			
			$this->db->where('account', $account);
			$data = array('password' => Auth::decode_pwd($pwd1),'update_time' => time());		
			if($this->db->update('bg_admin_user', $data)){
				status(200, '操作成功','','','closeCurrent','reload');
			}
		}
    }*/
        
    /**
     * 安全退出登录
     */
    public function logout(){
        $this->input->set_cookie('token','',-1);
        redirect('/login/index', 'refresh');
    }
}